﻿var BaseUrl = "";//RootUrl
var checkEnv = false;//环境检测是否通过
var initDataStatus = false;//是否创建成功
var installEnv = false;//是否创建成功
$(document).ready(function () {

    $("#install-wizard").steps({
        headerTag: "h1",
        bodyTag: "div",
        enableFinishButton: true,
        enableCancelButton:false,
        transitionEffect: "slide",
        labels: {
            cancel: "取消",
            current: "current step:",
            pagination: "Pagination",
            finish: "完成",
            next: "下一步",
            previous: "上一步",
            loading: "Loading ..."
        },
        onStepChanging: function (event, currentIndex, newIndex) {
           
            if (currentIndex == 0) {
                if (!$("#chkAgree")[0].checked) {
                    Notify.Error("请先同意协议在进行下一步","错误提示");
                    return false;
                }
            }
            if (currentIndex == 4 && !installEnv) {
                return false;
            }
           
            
            // Always allow going backward even if the current step contains invalid fields!
            if (currentIndex > newIndex) {
                if (currentIndex == 3) {
                    if ($(".check-task-status[closed='1']").length != 4) {
                        return false;
                    }
                }
                return true;
            }

            // Forbid suppressing "Warning" step if the user is to young
            //if (newIndex === 3 && Number($("#age").val()) < 18) {
            //    return false;
            //}

            var form = $(this);

            // Clean up if user went backward before
            if (currentIndex < newIndex) {
                // To remove error styles
                $(".body:eq(" + newIndex + ") label.error", form).remove();
                $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
                if (currentIndex == 3 && !checkEnv) {
                    return false;
                }
            }
            
            // Disable validation on fields that are disabled or hidden.
            form.validate().settings.ignore = ":disabled,:hidden";

            // Start validation; Prevent going forward if false
            return form.valid();
        },
        onStepChanged: function (event, currentIndex, priorIndex) {
            $("ul[aria-label='Pagination']").find("a[href='#finish']").parent().addClass("hidden");
            if (currentIndex == 3) {
                $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().addClass("hidden");
                $("ul[aria-label='Pagination']").find("a[href='#next']").parent().addClass("hidden");
                checkInstallEnv();
            }
          
            if (currentIndex == 4) {
                //$("ul[aria-label='Pagination']").find("a[href='#finish']").parent().removeClass("hidden");
                $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().addClass("hidden");
               // $("ul[aria-label='Pagination']").find("a[href='#next']").parent().addClass("hidden");
                InstallEnv();
            }
         
        },
        onFinishing: function (event, currentIndex) {
            var form = $(this);
            form.validate().settings.ignore = ":disabled";
            return form.valid();
        },
        onFinished: function (event, currentIndex) {
           
            window.location.href = "/";
        }
    });

    $("#install-wizard").CustomForm({ IsValidate: true });
    $("ul[aria-label='Pagination']").find("a[href='#finish']").parent().addClass("hidden");
    $("#initdata-wizard").steps({
        headerTag: "h1",
        bodyTag: "div",
        enableFinishButton: false,
        enableCancelButton: false,
        transitionEffect: "slide",
        labels: {
            cancel: "取消",
            current: "current step:",
            pagination: "Pagination",
            finish: "安装",
            next: "下一步",
            previous: "上一步",
            loading: "Loading ..."
        },
        onTabClick: function () {
            return false;
        },
        onStepChanging: function (event, currentIndex, newIndex) {
           
            if (currentIndex == 4) {
                if ($("ul[aria-label='Pagination']").find("a[href='#previous']").parent().hasClass("disabled")) {//开始安装后不允许返回上一步
                    return false;
                }
            }

            if (currentIndex > newIndex) {
                return true;
            }
            var form = $(this);

            // Clean up if user went backward before
            if (currentIndex < newIndex) {
                // To remove error styles
                $(".body:eq(" + newIndex + ") label.error", form).remove();
                $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
                if (currentIndex == 1 && !initDataStatus) {
                    return false;
                }
            }

            // Disable validation on fields that are disabled or hidden.
            form.validate().settings.ignore = ":disabled,:hidden";

            // Start validation; Prevent going forward if false
            return form.valid();
        },
        onStepChanged: function (event, currentIndex, priorIndex) {
            if (currentIndex == 1) {
                $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().addClass("disabled");
                CreateInitDataEnv();
            }
        },
        onFinishing: function (event, currentIndex) {
            var form = $(this);
            form.validate().settings.ignore = ":disabled";
            return form.valid();
        },
        onFinished: function (event, currentIndex) {
          

        }
    });
    $("#initdata-wizard").CustomForm({ IsValidate: true });
});
//环境检测
function checkInstallEnv() {
    $(".initdata-result").html("<i class=\"fa fa-spinner fa-spin pull-left\"></i>系统验证中，请稍候......");
    Ajax({
        url: BaseUrl + "/install/home/checkInstallEnv",
        data: FormHelper.getFormData($("#install-wizard")),
        success: function (result, message) {
            var html = "";
          
            for (var i = 0; i < result.length; i++) {

                html += "<p id='task-" + result[i].TaskId + "' class='check-task-status' style='color:" + (result[i].IsSuccess ? "" : "red") + ";'>";
                html += result[i].TaskName + "：<i class=\"fa fa-spinner fa-spin pull-left\"></i>正在处理中";
                html += "</p>";
            }
            $(".checkinstallenv").html(html);
            var task = result[0];
            var timer = window.setInterval(function () {
                checkTaskStatus(task, timer);
            }, 1000);
            var task1 = result[1];
            var timer1 = window.setInterval(function () {
                checkTaskStatus(task1, timer1);
            }, 1000);
            var task2 = result[2];
            var timer2 = window.setInterval(function () {
                checkTaskStatus(task2, timer2);
            }, 1000);
            var task3 = result[3];
            var timer3 = window.setInterval(function () {
                checkTaskStatus(task3, timer3);
            }, 1000);
            var timer4 = window.setInterval(function () {
                if ($(".check-task-status[closed='1']").length == 4) {
                    checkEnv =true;
                    $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().removeClass("hidden");
                    if ($(".check-task-status[status='1']").length == 4) {
                        $("ul[aria-label='Pagination']").find("a[href='#next']").parent().removeClass("hidden");
                    }
                    window.clearInterval(timer4);
                }
            },1500);
        }
    });
}
//验证线程是否成功
function checkTaskStatus(task, timer) {
    Ajax({
        url: BaseUrl + "/install/home/CheckTaskStatus",
        data: { taskId: task.TaskId},
        success: function (result, message) {
            $("#task-" + task.TaskId).html(task.TaskName + "：<i class=\"fa fa-spinner fa-spin pull-left\"></i>正在处理中," + (result.Message != null ? result.Message:""));
            if (!result.IsOpen) {
                window.clearInterval(timer);
               
                $("#task-" + task.TaskId).html(result.TaskName + "：" + (result.IsSuccess ? "成功" : "失败" + result.Message));
                $("#task-" + task.TaskId).css({ "color": (result.IsSuccess ? "#2f4050" : "red") });
                $("#task-" + task.TaskId).attr({ "status": (result.IsSuccess ? "1" : "0") });
                $("#task-" + task.TaskId).attr({ "closed": "1" });
                RemoveTask(result.TaskId);
            }
        }
    });
}
//删除任务
function RemoveTask(taskId) {
    Ajax({
        url: BaseUrl + "/install/home/CheckTaskStatus",
        data: { taskId: taskId},
        success: function (result) {
            console.log(taskId+"任务删除成功");
        }
    });
}
///系统安装
function InstallEnv() {
    installEnv = false;
    Ajax({
        url: BaseUrl + "/install/home/InstallDbEnv",
        data: FormHelper.getFormData($("#install-wizard")),
        timeout:3000,
        success: function (result, message) {
            var html = "";

            html += "<p id='task-" + result.TaskId + "' class='install-task-status' style='color:" + (result.IsSuccess ? "" : "red") + ";'>";
            html += result.TaskName + "：<i class=\"fa fa-spinner fa-spin pull-left\"></i>正在处理中";
                html += "</p>";
            $(".installenv").html(html);
            var task = result;
            var timer = window.setInterval(function () {
                checkTaskStatus(task, timer);
            }, 1000);
            var timer4 = window.setInterval(function () {
                if ($(".install-task-status[closed='1']").length == 1) {
                    if ($(".install-task-status[status='1']").length == 1) {
                        InitialEnv();
                    }
                    window.clearInterval(timer4);
                }
            }, 1200);
        }
    });
}
//初始化数据
function InitialEnv() {
    Ajax({
        url: BaseUrl + "/install/home/InitialEnv",
        data: FormHelper.getFormData($("#install-wizard")),
        timeout: 3000,
        success: function (result, message) {
            var html = "";
          
            for (var i = 0; i < result.length; i++) {
                html += "<p id='task-" + result[i].TaskId + "' class='initial-task-status' style='color:" + (result[i].IsSuccess ? "" : "red") + ";'>";
                html += result[i].TaskName + "：<i class=\"fa fa-spinner fa-spin pull-left\"></i>正在处理中";
                html += "</p>";
            }
            $(".installenv").append(html);
            var task = result[0];
            var timer = window.setInterval(function () {
                checkTaskStatus(task, timer);
            }, 1000);
            var task1 = result[1];
            var timer1 = window.setInterval(function () {
                checkTaskStatus(task1, timer1);
            }, 1000);
            var timer4 = window.setInterval(function () {
                if ($(".initial-task-status[closed='1']").length == 2) {
                    installEnv = true;
                    window.clearInterval(timer4);
                    if ($(".initial-task-status[status='1']").length < 2) {//异常时显示上一步
                        $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().removeClass("hidden");
                    }
                    else {//正常时显示完成
                        $("ul[aria-label='Pagination']").find("a[href='#finish']").parent().removeClass("hidden");
                    }
                    
                  
                }
            }, 1500);
        }
    });
}
///生成初始化数据
function CreateInitDataEnv() {

    initDataStatus = false;
    Ajax({
        url: BaseUrl + "/install/initdata/createdata",
        data: FormHelper.getFormData($("#initdata-wizard")),
        success: function (result) {
            var html = "";
            html += "<p id='task-" + result.TaskId + "' class='install-task-status' style='color:" + (result.IsSuccess ? "" : "red") + ";'>";
            html += result.TaskName + "：<i class=\"fa fa-spinner fa-spin pull-left\"></i>正在处理中";
            html += "</p>";
            $(".initdata-result").html(html);
            var task = result;
            var timer = window.setInterval(function () {
                checkTaskStatus(task, timer);
            }, 1000);
            var timer4 = window.setInterval(function () {
                if ($(".install-task-status[closed='1']").length == 1) {
                    if ($(".install-task-status[status='1']").length == 1) {
                    }
                    $("ul[aria-label='Pagination']").find("a[href='#previous']").parent().removeClass("disabled");
                    window.clearInterval(timer4);
                }
            }, 1200);
          
        },
        error: function (message) {
            $(".initdata-result").html(message);
        },
        complete: function () {
         
        }
    });
}